package se.webbzon.boltzmann.menu;

import java.awt.Image;
import java.awt.image.ImageObserver;

import se.webbzon.boltzmann.sound.SoundUtils;
import se.webbzon.oschi01.font.VerticalAlignment;
import se.webbzon.oschi01.resourceset.ResourceSet;
import se.webbzon.oschi01.worldcamera.WorldCameraPane;

public abstract class MButton extends MItem {
	
	// The layout of this button
	private final ButtonLayout layout;
	
	// The image resource set of the button
	private ResourceSet<Image> imageSet;
	
	// The text of this button
	private MText text;
	
	// Whatever the button has been pressed
	private volatile boolean pressed;
	
	/*============================================================
	Constructors
	============================================================*/
	
	public MButton(ImageObserver observer, ButtonLayout layout, boolean isLong, String text) {
		this.layout = layout;
		this.text = new MText(layout,text);
		this.text.setVAlignment(VerticalAlignment.MIDDLE);
		this.text.setShadow(true);
		if (isLong)
			this.imageSet = layout.getLongButtonImage();
		else
			this.imageSet = layout.getShortButtonImage();
		setWidth(this.imageSet.get(0).getWidth(observer));
		setHeight(this.imageSet.get(0).getHeight(observer));
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	/** This method is invoked when the button is clicked. **/
	public abstract void onClick(GameMenu menu);
	
	/** Returns the text of this game menu button. **/
	public String getText() {
		return text.getText();
	}
	
	/** Sets the text of this game menu button. **/
	public void setText(String text) {
		this.text.setText(text);
	}
	
	@Override public void setFocus(boolean focus) {
		if (hasFocus() == false && focus == true)
			SoundUtils.playSound("menu_browse");
		super.setFocus(focus);
	}

	@Override public void onDraw(GameMenu menu, WorldCameraPane hud) {
		int x, index;
		int y = getY();
		if (hasFocus()) {
			x = getX() + 8;
			if (pressed)
				index = 1;
			else
				index = 0;
		} else {
			x = getX();
			index = 0;
		}
		hud.drawImage(imageSet.get(index), x, y);
		text.draw(hud, x + layout.getTextX(), y + layout.getTextY());
	}

	@Override public void onPress(GameMenu menu, int x, int y) {
		if (isWithin(x,y))
			pressed = true;
	}

	@Override public void onRelease(GameMenu menu, int x, int y) {
		if (pressed && isWithin(x,y)) {
			SoundUtils.playSound("menu_select");
			onClick(menu);
		}
		pressed = false;
	}

	@Override public boolean isDraggable() {
		return false;
	}
	
	@Override public boolean isFocusable() {
		return true;
	}

}
